import dataPreferences from '@ohos.data.preferences'

// 实例名字
const PREFERENCES_NAME = 'myPreferences'

class PreferencesUtil {

  // getPreferences的promise
  preferencesPromise: Promise<dataPreferences.Preferences>

  /**
   * 创建preferences实例
   * @param context
   */
  createPreferences(context) {
    this.preferencesPromise = dataPreferences.getPreferences(context, PREFERENCES_NAME);
  }

  /**
   * 保存token
   * @param token
   */
  saveKeyValue(key: string, value: string) {
    this.preferencesPromise.then(async preferences => {
      await preferences.put(key, value)
      preferences.flush();
    })
  }

  /**
   * 获取key的值
   * @param key 健值
   * @returns value
   */
  async getKeyValue(key: string) {
    // preferences 实例
    const preferences = await this.preferencesPromise
    // value
    const value = await preferences.get(key, '')
    return value
  }

  /**
   * 获取所有健值对的Object对象
   */
  async getAll() {
    // preferences 实例
    const preferences = await this.preferencesPromise
    // 所有数据对象
    const allInfo = await preferences.getAll()
    return allInfo
  }

  /**
   * 删除key-value
   * @param key
   * @returns
   */
  async deleteKeyValue(key: string) {
    // preferences 实例
    const preferences = await this.preferencesPromise
    return preferences.delete(key)
  }

  /**
   * 清除实例所有的存储
   * @returns
   */
  async clearAll() {
    // preferences 实例
    const preferences = await this.preferencesPromise
    return preferences.clear()
  }
}

// 创建 对象，导出
let preferencesUtil: PreferencesUtil = new PreferencesUtil()

export default preferencesUtil